#include "telbook.h"

void create_book(char *str[])
{
   char action_buffer[40];
   char choice;
   int index = atoi(str[3]);
   if(index < 1)
    {
     printf("Invalid size\n");
     exit(0);
    }
   int fd;
   //create file while checking if it exists
   if((fd = open(str[2],O_WRONLY|O_CREAT|O_EXCL,PERMS)) < 0)
    {
     if(errno == EEXIST)
      {//prompt the user before overwriting
       printf("File already exists!Do you want to overwrite it?(y/n)\n");
       scanf("%c",&choice);
       if(choice == 'n')
        exit(0);
       else
         {
          if((fd = open(str[2],O_WRONLY|O_TRUNC,PERMS)) < 0)
           {
            perror("Failed to create file");
            exit(0);
           }
         } 

      } 
     
     else
        {//take care of other errors
         perror("Failed to create file");
         exit(0);
        }    
    } 
//create hole 
   if ((lseek(fd,index*SIZE,SEEK_SET)) == -1)
    {
      perror("Failed to create file:");
      exit(0);
    }

//delimit the file for the hole to appear
   if((write(fd,"~",1))!=1)
  {
   perror("Failed to write:");
   exit(0);
  }
//create action message for the log
  sprintf(action_buffer,"%s %s","Created file:",str[2]);
//call write_log
  write_log(action_buffer);
   close(fd);
 }

